package com.jackrain.clouddata.oms.mq;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.SendResult;
import com.jackrain.nea.core.db.Tools;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

import java.sql.Timestamp;
import java.util.Date;

/**
 * Created by nathan on 2017/8/23.
 */
@Aspect
@Slf4j
public class MonitorMqAspect {

    @Before(value="execution(* com.aliyun.openservices.ons.api.bean.ProducerBean.send(..))&& args(message)",argNames= "point,message")
    public void beforeSend(JoinPoint point, Message message) {
        try {

            String[] tags = message.getTag().split(":");
            String tag = null;
            if(tags.length > 0){
                tag = tags[0];
            }

//            String clientIdSql = "SELECT AD_CLIENT_ID FROM OMS_TAG WHERE ISACTIVE='Y' AND TAGNAME = ?";
//            JSONObject clientJson = QueryEngine.getInstance().doQueryObject(clientIdSql,new Object[]{tag});
//            if (clientJson == null){
//                throw new NDSException("公司ID未找到!");
//            }
//            Long clientId = clientJson.getLong("AD_CLIENT_ID");


            //查询topicid
            String topicSql = "SELECT ID FROM OMS_TOPIC WHERE ISACTIVE='Y' AND TOPIC=?";
            JSONObject topicJson = QueryEngine.getInstance().doQueryObject(topicSql,new Object[]{message.getTopic()});
//            if (clientJson == null){
//                throw new NDSException("TOPIC未找到");
//            }

            String insertSql = "INSERT INTO ONS_SENDMONITOR (ID,AD_CLIENT_ID,PTYPE,TOPICID,TAG,STATE,MSGKEY,MSGID,CONSUMER_ERROR,CREATIONDATE,MODIFIEDDATE)" +
                    "values (?,?,?,?,?,?,?,?,?,?,?)";
            QueryEngine.getInstance().
                    executeUpdate(insertSql,
                            new Object[]{Tools.getSequence("ONS_SENDMONITOR"),0,1,
                                    topicJson.get("ID"), tag,0,message.getKey(),message.getMsgID(),"N", new Timestamp((new Date()).getTime()),new Timestamp((new Date()).getTime())});

        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
    }


    @AfterReturning(value="execution(* com.aliyun.openservices.ons.api.bean.ProducerBean.send(..))&& args(message)",returning="result",argNames= "point,result,message")
    public void afterSend(JoinPoint point, SendResult result, Message message) {
        try {
            String updateSql = "UPDATE ONS_SENDMONITOR SET PDESC=?,STATE=? where MSGKEY=?";
            if(result == null){
                QueryEngine.getInstance().
                        executeUpdate(updateSql,
                                new Object[]{message.getBody().toString(),0,message.getKey()});

            }else{
                QueryEngine.getInstance().
                        executeUpdate(updateSql,
                                new Object[]{"",1,message.getKey()});
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
    }

    @AfterThrowing(value="execution(* com.aliyun.openservices.ons.api.bean.ProducerBean.send(..))&& args(message)",throwing = "e",argNames= "joinPoint,e,message")
    public  void doAfterThrowing(JoinPoint joinPoint,Throwable e,Message message) {
        try {
            String updateSql = "UPDATE ONS_SENDMONITOR SET PDESC=?,STATE=? where MSGKEY=?";
            QueryEngine.getInstance().
                    executeUpdate(updateSql,
                            new Object[]{message.getBody().toString(),0,message.getKey()});

        } catch (Exception exp) {
            log.error(exp.getMessage(),exp);
        }
    }
}
